package com.cndw.kungfu.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsQueue;
import com.cndw.kungfu.config.ConstantsTask;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Queue;
import com.cndw.kungfu.domain.Skill;
import com.cndw.kungfu.domain.SkillMode;
import com.cndw.kungfu.domain.Union;
import com.cndw.kungfu.domain.UnionMember;
import com.cndw.kungfu.domain.UnionSkillConfig;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.skill.PlayerSkill;
import com.cndw.kungfu.model.skill.SkillGird;
import com.cndw.kungfu.model.skill.SkillManger;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.model.union.UnionServer;
import com.cndw.kungfu.vo.QueueVO;
import com.cndw.kungfu.vo.SkillModeVO;
import com.cndw.kungfu.vo.SkillVO;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 技能管理面板
 * 
 * @author fantadust
 * @date 2011-5-6 上午09:59:51
 */
@Controller
public class SkillController {
	@Autowired
	private SkillManger skillManger;

	/**
	 * 加载我的技能
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage show(Session session, int skillType) {

		PlayerSkill playerSkill = Context.getSkillServer().getPlayerSkill(session.getUid());

		List<SkillVO> skillVOs = new ArrayList<SkillVO>();
		for (Skill skill : playerSkill.getSkillMap().values()) {
			skillVOs.add(skill.toSkillVO());
		}
		List<SkillModeVO> skillModeList = Context.getSkillServer().loadSkillModeVOs(session.getUid(), skillType);

		List<Queue> queues = Context.getQueueServer().getQueueIds(session.getUid(), false);
		List<QueueVO> skillQueues = new ArrayList<QueueVO>();
		if (queues != null && !queues.isEmpty()) {
			Iterator<Queue> it = queues.iterator();
			while (it.hasNext()) {
				Queue queue = (Queue) it.next();
				if (queue.getType() == ConstantsQueue.typeOnSkill) {
					skillQueues.add(queue.toQueueVO());
				}
			}
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		int crystalStone = player.getPlayerBoxs().getStackNum(GoodsEffectConfig.skillStoneGoodsId);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("skillList", skillVOs);
		map.put("skillModeList", skillModeList);
		map.put("skillQueues", skillQueues);
		map.put("queuesMax", Context.getSkillServer().getQueueMax(session.getUid()));
		map.put("crystalStone", crystalStone);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示内功界面
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage showStrengthSkill(Session session) {
		long playerId = session.getUid();
		PlayerSkill playerSkill = Context.getSkillServer().getPlayerSkill(playerId);

		List<SkillVO> skillVOs = new ArrayList<SkillVO>();
		for (Skill skill : playerSkill.getSkillMap().values()) {
			skillVOs.add(skill.toSkillVO());
		}
		// Player player = Context.getPlayerServer().getByPlayerId(playerId);

		List<SkillModeVO> strengthVos = new ArrayList<SkillModeVO>();
		for (SkillMode skillMode : Context.getSkillServer().getStrengthSkills()) {
			SkillModeVO e = skillMode.toSkillModeVO();
			if (e.getLevel() > playerSkill.getLevel(e.getSkillLibId())) {
				e.initStudyBook(playerId);
			}

			strengthVos.add(e);
		}

		List<Queue> queues = Context.getQueueServer().getQueueIds(playerId, false);
		List<QueueVO> skillQueues = new ArrayList<QueueVO>();
		if (queues != null && !queues.isEmpty()) {
			Iterator<Queue> it = queues.iterator();
			while (it.hasNext()) {
				Queue queue = (Queue) it.next();
				if (queue.getType() == ConstantsQueue.typeOnStrength) {
					skillQueues.add(queue.toQueueVO());
				}
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("skillVOs", skillVOs);
		map.put("strengthVos", strengthVos);
		map.put("skillQueues", skillQueues);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 学习技能
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	public ResponseMessage study(Session session, int id) {
		long playerId = session.getUid();
		SkillMode skillMode = Context.getSkillServer().getSkillMode(id);

		if (skillMode == null) {
			return null;
		}

		List<Queue> queues = Context.getQueueServer().getQueueIds(playerId, false);
		if (queues != null && !queues.isEmpty()) {
			Iterator<Queue> it = queues.iterator();
			while (it.hasNext()) {
				Queue queue = (Queue) it.next();
				if (queue.getType() == ConstantsQueue.typeOnStrength && skillMode.getType() == SkillMode.typeStrength) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.study.havestrength"));
				}
				if (queue.getType() == ConstantsQueue.typeOnSkill) {
					if (queue.getParam1() == id) {
						return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.study.havestudy"));
					}
				}
			}
		}

		if (skillMode.getCostTime() > 0 && queues.size() >= Context.getSkillServer().getQueueMax(playerId)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.study.havanoqueue"));
		}

		int skillLibId = skillMode.getSkillLibId();

		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (skillMode.getPlayerLevel() > player.getLevel()) {
			return null;// 玩家等级不够
		} else if (skillMode.getType() == SkillMode.typeVocational && skillMode.getVocationId() != player.getVocationId()) {
			return null;// 玩家职业不同
		} else if (skillMode.getType() == SkillMode.typeMonster || skillMode.getType() == SkillMode.typePet) {
			return null;
		}
		PlayerSkill playerSkill = Context.getSkillServer().getPlayerSkill(playerId);

		Map<Integer, Skill> skillMap = playerSkill.getSkillMap();
		Skill skillHaved = null;
		if (skillMap.containsKey(skillLibId)) {
			skillHaved = skillMap.get(skillLibId);
			if (skillHaved.getLevel() >= skillMode.getLevel()) {
				return null;
			} else if (skillHaved.getLevel() + 1 < skillMode.getLevel()) {
				return null;
			}
		} else if (skillMode.getLevel() != 1) {
			return null;
		}
		if (skillMode.getFrontSkillId() > 0) {
			SkillMode eMode = Context.getSkillServer().getSkillMode(skillMode.getFrontSkillId());
			if (eMode != null) {
				Skill eSkill = skillMap.get(eMode.getSkillLibId());
				if (eSkill == null || eSkill.getLevel() < eMode.getLevel()) {
					return null;
				}
			}
		}
		PlayerBoxs playerBoxs = null;
		// 判断技能书 金钱
		if (skillMode.getStudyBookId() > 0) {
			playerBoxs = Context.getGoodsServer().getPlayerBoxs(playerId);
			if (playerBoxs.getStackNum(skillMode.getStudyBookId()) <= 0) {
				GoodsMode goodsMode = Context.getGoodsServer().getModeById(skillMode.getStudyBookId());
				return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.study.nobook", goodsMode.getName()));
			}
		}
		if (player.getAsset() < skillMode.getAsset()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
		}
		if (player.getGoldAll() < skillMode.getGold()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		if (skillMode.getStoneNum() > 0) {
			if (playerBoxs.getStackNum(GoodsEffectConfig.skillStoneGoodsId) < skillMode.getStoneNum()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.study.nostone"));
			}
		}
		if (skillMode.getStudyBookId() > 0) {
			playerBoxs.costGoods(skillMode.getStudyBookId(), 1);
		}
		if (skillMode.getAsset() > 0) {
			player.alterAsset(-skillMode.getAsset());
		}
		if (skillMode.getGold() > 0) {
			player.alterGoldAll(-skillMode.getGold());
		}
		if (skillMode.getStoneNum() > 0) {
			playerBoxs.costGoods(GoodsEffectConfig.skillStoneGoodsId, skillMode.getStoneNum());
		}

		Map<String, Object> map = new HashMap<String, Object>();

		if (skillMode.getCostTime() > 3) {
			Queue queue = new Queue();
			int beginTime = TimeProcesser.getUnixTime();
			int needTime = skillMode.getCostTime();

			int endTime = beginTime + needTime - 3;

			queue.setPlayerId(playerId);
			if (skillMode.getType() == SkillMode.typeVocational) {
				queue.setType(ConstantsQueue.typeOnSkill);
			} else {
				queue.setType(ConstantsQueue.typeOnStrength);
			}
			queue.setFuncType(ConstantsQueue.funcTypeStudySkill);
			queue.setBeginTime(beginTime);
			queue.setEndTime(endTime);
			queue.setParam1(id);
			queue.setNextExecTime(endTime);
			queue.setTitle(LanguageLib.get("skill.study.title") + skillMode.getName());
			Context.getQueueServer().insertQueue(queue);
		} else {

			Context.getSkillServer().studySkill(playerId, id);
			if (skillMode.getType() == SkillMode.typeStrength || skillMode.getType() == SkillMode.typeMartial) {

				map.put("player", player.toPlayerVO());
			}else{
				Context.getPlayerServer().clacScore(player);
			}

		}
		player.commitSync();// 提交同步
		/**
		 * 装备武功
		 */
		Context.getTaskServer().notifyToSpark(playerId, ConstantsTask.spark5SkillUpgrade, 1);
		if (SkillMode.typeStrength == skillMode.getType()) {
			Context.getTaskServer().notifyToSpark(playerId, ConstantsTask.spark23SkillStrength, 1);
		}

		// 添加“人物-学习/升级武功”日志
		LogServer.recordLog(player, ConstantsLog.player, 30001, skillMode.getName(), id, skillMode.getStoneNum(), skillMode.getAsset(), skillMode.getGold(),
				skillMode.getStudyBookId(), skillMode.getLevel(),
				skillMode.getStudyBookId() > 0 ? Context.getGoodsServer().getModeById(skillMode.getStudyBookId()).getName() : "无");

		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("asset", player.getAsset());

		return ResponseMessage.getSuccMessage(map);// 不做直接跳转

	}

	/**
	 * 加速完成学习
	 * 
	 * @param session
	 * @param QueueId
	 * @return
	 */
	public ResponseMessage fastComplete(Session session, int QueueId) {
		long playerId = session.getUid();

		List<Queue> queues = Context.getQueueServer().getQueueIds(playerId, false);
		Queue queue = null;
		if (queues != null && !queues.isEmpty()) {
			Iterator<Queue> it = queues.iterator();
			while (it.hasNext()) {
				Queue tmpQueue = it.next();
				if (tmpQueue.getId() == QueueId && (tmpQueue.getType() == ConstantsQueue.typeOnSkill || tmpQueue.getType() == ConstantsQueue.typeOnStrength)) {
					queue = tmpQueue;
					break;
				}
			}
		}
		if (queue == null) {
			return null;
		}
		int laveTime = queue.getEndTime() - TimeProcesser.getUnixTime();
		if (laveTime + 3 <= 0) {// 还有3秒不能加速
			return null;
		}
		int costGold = NumberProcesser.ceil(laveTime, ConstantsModel.accelerateSecondOfGold);
		if (costGold < 0) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getGoldAll() < costGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		player.alterGoldAll(-costGold);

		queue.setEndTime(TimeProcesser.getUnixTime());

		Context.getQueueServer().immediately(queue);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("costGold", costGold);
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());

		if (queue.getType() == ConstantsQueue.typeOnStrength) {
			map.put("player", player.toPlayerVO());
		}

		LogServer.costEventLog(playerId, costGold, ConstantsCost.skillFast);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 遗忘技能
	 * 
	 * @param session
	 * @param skillId
	 * @return
	 */
	public ResponseMessage forget(Session session, int skillId) {
		skillManger.hashCode();
		return null;
	}

	/**
	 * 加载技能栏
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage loadShortcut(Session session) {
		long playerId = session.getUid();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("shortcutList", Context.getSkillServer().loadShortcut(playerId));
		SkillMode skillMode = Context.getSkillServer().getSkillMode(ConstantsModel.defaultSkillId);
		map.put("defaultSkillMode", skillMode.toSkillModeVO());

		return ResponseMessage.getSuccMessage(map);

	}

	/**
	 * 设置技能栏
	 * 
	 * @param session
	 * @param id
	 * @param oldPostion
	 * @param position
	 * @return
	 */
	public ResponseMessage shortcut(Session session, int id, int oldPostion, int position) {
		PlayerSkill playerSkill = Context.getSkillServer().getPlayerSkill(session.getUid());
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		if (position == 0 || position > PlayerSkill.skillGirdMax) {
			playerSkill.shortcutRemove(oldPostion);

		} else if (oldPostion > 0) {
			SkillGird sourceSkillGird = playerSkill.shortcutGet(oldPostion);
			if (sourceSkillGird == null) {
				return null;
			}
			playerSkill.shortcutRemove(oldPostion);
			SkillGird targetSkillGrid = playerSkill.shortcutGet(position);
			if (targetSkillGrid != null) {
				targetSkillGrid.setPosition(oldPostion);
				playerSkill.shortcutPut(targetSkillGrid);
			}
			sourceSkillGird.setPosition(position);
			playerSkill.shortcutPut(sourceSkillGird);

		} else {
			Collection<SkillGird> skillGirds = playerSkill.getShortcutGirds();
			SkillGird skillGird = new SkillGird();
			skillGird.setPosition(position);
			skillGird.setId(id);
			if (id < Constants.skillDifferenceGoods) {
				GoodsMode goodsMode = Context.getGoodsServer().getModeById(id);
				if (goodsMode == null) {
					return ResponseMessage.getFailMessage(false);
				}
				if (goodsMode.getAppId() != Constants.Goods_App_Drug || !goodsMode.isUseEnable()) {
					return ResponseMessage.getFailMessage(false);
				} else if (goodsMode.getPlayerLevel() > player.getLevel()) {
					return ResponseMessage.getFailMessage(false);
				}

				skillGird.setAreGoods(true);
				for (SkillGird e : skillGirds) {
					if (e.isAreGoods() && e.getPosition() != position) {

						GoodsMode oldMode = Context.getGoodsServer().getModeById(e.getId());
						if ((goodsMode.getValueA() > 0 && oldMode.getValueA() > 0) || goodsMode.getValueB() > 0 && oldMode.getValueB() > 0) {
							return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.shortcut.storesamedrugslimit", ConstantsModel.sameDrugsLimit));
						}
					}
				}

			} else {

				SkillMode skillMode = Context.getSkillServer().getSkillMode(id);
				if (skillMode == null || !skillMode.isOnlyBattleUse()) {
					return ResponseMessage.getFailMessage(false);
				}
				Skill skill = playerSkill.getSkillMap().get(skillMode.getSkillLibId());
				if (skill == null || skill.getLevel() < skillMode.getLevel()) {
					return ResponseMessage.getFailMessage(false);
				}
				for (SkillGird e : skillGirds) {
					if (e.isAreGoods() == false) {
						SkillMode oldMode = Context.getSkillServer().getSkillMode(e.getId());
						if (oldMode == null) {
							continue;
						}
						if (oldMode.getSkillLibId() == skillMode.getSkillLibId()) {
							playerSkill.shortcutRemove(e.getPosition());
							break;
						}
					}
				}
			}

			playerSkill.shortcutPut(skillGird);
		}
		Context.getPlayerServer().clacScore(player);
		player.commitSync();
		return loadShortcut(session);
	}

	/**
	 * 获取玩家已学习的帮派技能
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getPlayerUnionSkillInfo(Session session) {

		UnionServer server = Context.getUnionServer();
		int[] skillType = new int[] { 1, 2, 3, 4, 5, 6, 7, 9 };

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Union union = server.getUnionById(player.getUnionId());
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		List<UnionSkillConfig> skillList = new ArrayList<UnionSkillConfig>();
		for (int skill : skillType) {
			int level = player.getDataInfo().getUnionSkillLevel(skill);

			UnionSkillConfig config = server.getUnionSkillConfig(String.valueOf(skill) + level);
			if (!BlankUtils.isBlank(config)) {
				skillList.add(config);
			}

			config = server.getUnionSkillConfig(String.valueOf(skill) + (level + 1));
			if (!BlankUtils.isBlank(config)) {
				skillList.add(config);
			}

			if (union == null || BlankUtils.isBlank(union.getSkillMap())) {
				map.put(skill, 0);
			} else {
				map.put(skill, union.getSkillMap().get(skill));
			}
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("skillList", skillList);
		resultMap.put("unionSkill", map);
		if (union == null) {
			resultMap.put("playerResource", 0);
		} else {
			resultMap.put("playerResource", union.getMember(session.getUid()).getResource());
		}

		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 学习帮派技能
	 * 
	 * @param session
	 * @param type
	 * @return
	 */
	public ResponseMessage studyUnionSkill(Session session, int type) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Union union = Context.getUnionServer().getUnionById(player.getUnionId());
		if (union == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		int level = player.getDataInfo().getUnionSkillLevel(type) + 1;
		UnionSkillConfig nextConfig = Context.getUnionServer().getUnionSkillConfig(String.valueOf(type) + level);

		if (nextConfig == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.max"));
		}

		if (BlankUtils.isBlank(union.getSkillMap()) || union.getSkillMap().get(type).intValue() < nextConfig.getLevel()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.union.skillLevel"));
		}

		if (player.getAsset() < nextConfig.getUseAsset()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.union.asset"));
		}

		UnionMember member = union.getMember(player.getPlayerId());
		if (member.getResource() < nextConfig.getUseResource()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.union.resource"));
		}

		// 扣贡献度
		member.setResource(member.getResource() - nextConfig.getUseResource());
		Context.getUnionServer().updateMemberResource(member);

		// 扣资金
		player.alterAsset(-nextConfig.getUseAsset());

		// 修改技能等级
		player.getDataInfo().getUnionSkillMap().put(nextConfig.getType(), nextConfig.getLevel());
		Context.getPlayerServer().clacProperties(player);
		player.commitSync();
		player.getDataInfo().commitSync();
		
		LogServer.recordLog(player, ConstantsLog.union, 60018, nextConfig.getUseAsset(), nextConfig.getUseResource(), nextConfig.getName(), nextConfig.getLevel());

		// 更新个人资金
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("preConfig", nextConfig);
		resultMap.put("nextConfig", Context.getUnionServer().getUnionSkillConfig(String.valueOf(type) + (level + 1)));
		resultMap.put("resource", member.getResource());
		resultMap.put("asset", player.getAsset());
		resultMap.put("player", player.toPlayerVO());

		return ResponseMessage.ticpMsg(LanguageLib.get("skill.union.succ", nextConfig.getUseAsset(), nextConfig.getUseResource()), resultMap);
	}
}
